using System.Net.WebSockets;
using System.Reflection;
using System.Reflection.PortableExecutable;
using System.Text;
using Autofac;
using Autofac.Core;
using Autofac.Extensions.DependencyInjection;
using ESSManageService.API;
using ESSManageService.API.Filter;
using ESSManageService.Common.Helper;
using ESSManageService.Extensions;
using ESSManageService.IServices;
using ESSManageService.IServices.IBusinessServices;
using ESSManageService.Services;
using ESSManageService.Services.BusinessServices;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Hosting;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Host
    .UseServiceProviderFactory(new AutofacServiceProviderFactory())
    .ConfigureContainer<ContainerBuilder>(builder =>
    {
        builder.RegisterModule(new AutofacModuleRegister());
        builder.RegisterModule<AutofacPropertityModuleReg>();
    })
    .ConfigureLogging(logging =>
    {
        // 清除默认的日志提供程序，准备配置 Serilog 日志
        logging.ClearProviders();
    })
    .ConfigureAppConfiguration((hostingContext, config) =>
    {
        config.Sources.Clear();
        config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false);
    });

builder.Services.AddSingleton(new AppSettings(builder.Configuration));

builder.Services.AddControllers();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    // 修改 API 文档版本
    //c.SwaggerDoc("v1", new OpenApiInfo { Title = "ESSManageService.API", Version = "v1" });
    // 只开放模型过滤
    //c.SchemaFilter<MinimalSchemasFilter>();
    // 修改模型过滤器的注释
    //c.DocumentFilter<HideSchemasDocumentFilter>();

    #region 添加接口注释
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    c.IncludeXmlComments(xmlPath);
    c.DescribeAllParametersInCamelCase();
    c.CustomSchemaIds(type => type.FullName);
    #endregion

    #region Swagger增加可输入Token
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = "JWT授权令牌（直接输入Bearer+空格+令牌）",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        Scheme = "Bearer"
    });

    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[] {}
        }
    });
    #endregion
});

// 添加内存缓存
builder.Services.AddMemoryCache();
// 注册黑名单服务
builder.Services.AddScoped<ITokenBlacklistService, TokenBlacklistService>();
// 添加身份验证
builder.Services.AddJwtSetup();

builder.Services.AddSqlsugarSetup();
builder.Services.AddDbSetup();
builder.Services.AddInitializationHostServiceSetup();
builder.Host.AddSerilogSetup();

builder.Services.AddAutoMapperSetup();

builder.Services.AddClientWebSocketServiceSetup();

var app = builder.Build();


// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
        c.RoutePrefix = "ESSManage.api";  // 自定义路径  
    });
}

app.UseHttpsRedirection();

// 在验证和授权中间件之前
app.UseAuthentication();
app.UseAuthorization();

//app.UseWebSockets();
app.Services.GetService<ClientWebSocketService>()?.StartAsync(new CancellationToken()).Wait();

app.MapControllers();

//app.Urls.Add("http://*:9001");

app.Run();
